//调用原生方法的一些通用方法
const NativeHelper = {
  guid: function () {
    return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = (Math.random() * 16) | 0,
        v = c == 'x' ? r : (r & 0x3) | 0x8
      return v.toString(16)
    })
  },
  createCallBack(callback) {
    //先随机生成一个函数名字
    const callbackFuncName = 'func_' + this.guid()
    //将callback方法绑定到window对象
    window[callbackFuncName] = function (data) {
      //java回调此方法时执行原始的回调方法
      callback(typeof data === 'object' ? data : JSON.parse(data))
      // callback(data)
      //执行完成后删除绑定到window的方法
      delete window[callbackFuncName]
    }
    return callbackFuncName
  },
  callNative(functionname, params) {
    return new Promise((callback, reject) => {
      var callbackFuncName = this.createCallBack(callback)
      var request = {}
      request.method = functionname
      let newParams = []

      for (const obj of params) {
        if (typeof obj === 'object') {
          newParams.push(JSON.stringify(obj))
        } else {
          newParams.push(obj)
        }
      }
      request.param = newParams
      request.callback = callbackFuncName
      try {
        window.NativeApi.takeNativeAction(JSON.stringify(request))
      } catch (error) {
        console.log(error)
        reject()
      }
    })
  }
}
export default NativeHelper
